<template>
  <div>
    <ul class="list">
      <li class="item" v-for="item of letters" :key="item"  :ref="item" @click="handleLetterClick" @touchstart.prevent="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">{{item}}</li>
      <!-- .prevent: 事件修饰符 阻止touchstart的默认行为  -->
    </ul>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0, /* 优化性能 */
      timer: null /* 性能优化 函数节流 */
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      console.log(e.target.innerText)
      this.$emit('change', e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          /* const startY = this.$refs['A'][0].offsetTop */
          /* 获取A元素距离顶部的高度 */
          /* console.log(startY) */
          const touchY = e.touches[0].clientY - 79
          /* 获取当前手指的位置 减掉的79为最顶部绿色区域的部分 */
          /*  console.log(touchY) */
          /* const index = Math.floor((touchY - startY) / 20) */
          const index = Math.floor((touchY - this.startY) / 20)
          /* 算出当前手指华东的位置 对应的字母下标 */
          console.log(index)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 16)
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }

}
</script>

<style scoped>
  .list {
    font-size: .24rem;
    position: absolute;
    top: 1.58rem;
    right: 0;
    bottom: 0;
    width: .4rem;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .item {
    line-height: .4rem;
    text-align: center;
    color: #00bcd4
  }
</style>
